package com.xuanxing123.webapp.action.settings;

import com.opensymphony.xwork2.Preparable;
import com.xuanxing123.service.ModuleManager;
import com.xuanxing123.service.ProductTypeManager;
import com.xuanxing123.model.Module;
import com.xuanxing123.webapp.action.BaseAction;

import java.util.List;

public class ModuleAction extends BaseAction implements Preparable {
    private ModuleManager moduleManager;
    private ProductTypeManager productTypeManager;
    private List modules;
    private Module module;
    private Long id;
    private String query;

    public void setModuleManager(ModuleManager moduleManager) {
        this.moduleManager = moduleManager;
    }

    public ProductTypeManager getProductTypeManager() {
        return productTypeManager;
    }

    public void setProductTypeManager(ProductTypeManager productTypeManger) {
        this.productTypeManager = productTypeManger;
    }

    public List getModules() {
        return modules;
    }

    public List getProductTypeList()
    {
        return productTypeManager.getAll();
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String moduleId = getRequest().getParameter("module.id");
            if (moduleId != null && !moduleId.equals("")) {
                module = moduleManager.get(new Long(moduleId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        modules = moduleManager.search(query, Module.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Module getModule() {
        return module;
    }

    public void setModule(Module module) {
        this.module = module;
    }

    public String delete() {
        moduleManager.remove(module.getId());
        saveMessage(getText("module.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            module = moduleManager.get(id);
        } else {
            module = new Module();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (module.getId() == null);

        moduleManager.save(module);

        String key = (isNew) ? "module.added" : "module.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}